<template>
  <div class="order-confirm-container">
    <!-- 头部导航保持原有逻辑 -->
    <HeadNav title="确认订单"></HeadNav>
    
    <!-- 主内容区：左侧商品/地址等 + 右侧结算明细 -->
    <div class="order-content-wrapper">
      <!-- 左侧主体内容（收货地址、订单商品、备注等） -->
      <div class="order-main">
        <!-- 收货地址 -->
        <div class="address-section">
          <div class="section-title">收货地址</div>
          <div class="address-list">
            <div 
              class="address-item" 
              v-for="address in addresses" 
              :key="address.id"
              :class="{ 'active': address.id === selectedAddressId }"
              @click="selectAddress(address.id)"
            >
              <div class="address-info">
                <div class="name-phone">
                  <span class="name">{{ address.name }}</span>
                  <span class="phone">{{ address.phone }}</span>
                </div>
                <div class="detail">
                  {{ address.province }}{{ address.city }}{{ address.district }}{{ address.detail }}
                </div>
              </div>
              <div class="address-action">
                <el-button type="text" @click.stop="editAddress(address.id)">
                  <i class="el-icon-edit"></i>
                </el-button>
              </div>
            </div>
            <div class="add-address" @click="addNewAddress">
              <i class="el-icon-plus"></i>
              <span>添加新地址</span>
            </div>
          </div>
        </div>
        
        <!-- 订单商品 -->
        <div class="order-section">
          <div class="section-title">订单信息</div>
          <div class="order-goods">
            <div class="goods-item" v-for="(item, index) in orderItems" :key="index">
              <div class="goods-image">
                <img :src="getImageUrl(item.image)" :alt="item.name">
              </div>
              <div class="goods-info">
                <div class="goods-name">{{ item.name }}</div>
                <div class="goods-spec">{{ item.colorName }} / {{ item.capacityValue }}</div>
                <div class="goods-price">¥{{ item.price.toFixed(2) }}</div>
                <div class="goods-quantity">x{{ item.quantity }}</div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 订单备注 -->
        <div class="remark-section">
          <div class="section-title">订单备注</div>
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入备注信息（选填）"
            v-model="orderRemark"
            maxlength="100"
            show-word-limit
          >
          </el-input>
        </div>
      </div>
      
     <!-- 右侧结算明细栏 -->
     <div class="order-summary">
       <div class="summary-header">
         <h3 class="summary-title">结算明细</h3>
         <div class="summary-count" v-if="orderItems.length">共{{ orderItems.length }}件商品</div>
       </div>
       
       <div class="summary-content">
         <div class="summary-empty" v-if="!orderItems.length">
           <i class="el-icon-shopping-cart-1"></i>
           <span>购物车是空的</span>
         </div>
       </div>
       
       <div class="summary-footer">
         <div class="total-price">
           <span>合计：</span>
           <span class="price">¥{{ totalPrice.toFixed(2) }}</span>
         </div>
         <el-button 
           type="primary" 
           class="submit-btn"
           :loading="submitting"
           :disabled="!orderItems.length"
           @click="submitOrder"
         >
           {{ orderItems.length ? '立即结算' : '请添加商品' }}
         </el-button>
       </div>
     </div>
    </div>
  </div>
</template>

<script>
import HeadNav from '../components/HeadNav.vue'
// import request from '@/utils/request.js'; // 导入您封装的axios实例

export default {
  name: 'OrderConfirm',
  components: {
    HeadNav
  },
  data() {
    return {
      orderItems: [], // 只保留一个定义
      itemCount: 0,
      totalPrice: 0,
      selectedAddressId: 1,
      orderRemark: '',
      submitting: false,
      addresses: [
        {
          id: 1,
          name: '张三',
          phone: '13800138000',
          province: '北京市',
          city: '北京市',
          district: '朝阳区',
          detail: '建国路88号现代城A座1001室',
          isDefault: true
        },
        {
          id: 2,
          name: '李四',
          phone: '13900139000',
          province: '上海市',
          city: '上海市',
          district: '浦东新区',
          detail: '张江高科技园区科苑路88号',
          isDefault: false
        },
        {
          id: 3,
          name: '王五',
          phone: '13900139001',
          province: '广州市',
          city: '广东省',
          district: '天河区',
          detail: '珠江新城华夏路8号',
          isDefault: false
        }
      ]
    };
  },
  created() {
    this.parseOrderData(); // 只保留这个方法
	// 先不加载地址
    // this.loadAddresses();

    // 如果没有商品，跳回购物车
    if (this.orderItems.length === 0) {
      this.$message.warning('没有选择商品');
      this.$router.push('/cart');
    }
  },
  methods: {
    getImageUrl(relativePath) {
      try {
        return require(`@/assets/img/goods/${relativePath}`);
      } catch (e) {
        return require('@/assets/img/goods/dian-1.png');
      }
    },
    
    selectAddress(id) {
      this.selectedAddressId = id;
    },
    
    editAddress(id) {
      // 这里实现编辑地址逻辑
      console.log('编辑地址:', id);
      // 示例：this.$router.push(`/address/edit/${id}`)
    },
    
    addNewAddress() {
      // 这里实现添加新地址逻辑
      console.log('添加新地址');
      // 示例：this.$router.push('/address/add')
    },
    
     async submitOrder() {
          if (!this.selectedAddressId) {
            this.$message.warning('请选择收货地址');
            return;
          }
          
          this.submitting = true;
          
          try {
            // 模拟订单提交过程
            await new Promise(resolve => setTimeout(resolve, 1000));
            
            // 生成模拟订单ID (实际项目中由后端生成)
            const mockOrderId = 'mock_' + Date.now();
            
            // 跳转到支付页面
            this.$router.push({
              path: '/payment',
              query: {
                orderId: mockOrderId,
                amount: this.totalPrice
              }
            });
            
          } catch (error) {
            console.error('提交订单失败:', error);
            this.$message.error('提交订单失败');
          } finally {
            this.submitting = false;
          }
        },
    
    loadAddresses() {
      // 这里调用API获取用户地址列表
      // 示例：
      // api.getAddresses().then(res => {
      //   this.addresses = res.data;
      //   const defaultAddress = this.addresses.find(a => a.isDefault);
      //   if (defaultAddress) {
      //     this.selectedAddressId = defaultAddress.id;
      //   }
      // });
    },
    
    parseOrderData() {
      if (this.$route.query.items) {
        try {
          // 正确的解码和解析顺序
          const decoded = decodeURIComponent(this.$route.query.items);
          this.orderItems = JSON.parse(decoded);
          this.totalPrice = parseFloat(this.$route.query.total || 0);
          this.itemCount = parseInt(this.$route.query.count || 0);
        } catch (e) {
          console.error('解析订单数据失败:', e);
          this.$router.push('/cart');
        }
      } else {
        this.$router.push('/cart');
      }
    }
  }
};
</script>

<style scoped>
.order-confirm-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

.order-content-wrapper {
  display: flex;
  gap: 20px;
  margin-top: 20px;
}

/* 左侧主体内容 */
.order-main {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

/* 右侧结算栏 */
.order-summary {
  width: 300px;
  position: sticky;
  top: 20px;
  height: fit-content;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 15px;
  color: #333;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

/* 地址部分样式 */
.address-list {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.address-item {
  display: flex;
  width: 28%;
  padding: 15px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
}

.address-item:hover {
  border-color: #ff6700;
}

.address-item.active {
  border-color: #ff6700;
  background-color: #fff8f0;
}

.address-info {
  flex: 1;
}

.name-phone {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.name {
  font-weight: 600;
  margin-right: 15px;
}

.phone {
  color: #666;
}

.detail {
  color: #666;
  font-size: 14px;
  line-height: 1.5;
}

.address-action {
  display: flex;
  align-items: center;
}

.add-address {
  display: flex;
  align-items: center;
  justify-content: center;
  width: calc(50% - 8px);
  height: 100px;
  border: 1px dashed #e0e0e0;
  border-radius: 6px;
  color: #999;
  cursor: pointer;
  transition: all 0.3s;
}

.add-address:hover {
  border-color: #ff6700;
  color: #ff6700;
}

.add-address i {
  margin-right: 5px;
}

/* 商品部分样式 */
.order-goods {
  margin-bottom: 20px;
}

.goods-item {
  display: flex;
  padding: 15px 0;
  border-bottom: 1px solid #f5f5f5;
}

.goods-image {
  width: 80px;
  height: 80px;
  margin-right: 15px;
}

.goods-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.goods-info {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.goods-name {
  width: 100%;
  font-size: 15px;
  margin-bottom: 5px;
}

.goods-spec {
  width: 50%;
  color: #999;
  font-size: 13px;
}

.goods-price {
  width: 25%;
  color: #ff6700;
  font-weight: 600;
}

.goods-quantity {
  width: 25%;
  text-align: right;
  color: #666;
}

/* 结算区域样式 */
.summary-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100px;
  color: #999;
}

.summary-empty i {
  font-size: 40px;
  margin-bottom: 10px;
}

.summary-tip {
  color: #999;
  font-size: 13px;
  margin-bottom: 20px;
}

.total-price {
  text-align: right;
  font-size: 16px;
  margin: 20px 0;
}

.price {
  color: #ff6700;
  font-size: 20px;
  font-weight: 600;
}

.submit-btn {
  width: 100%;
  height: 50px;
  font-size: 16px;
  background-color: #ff6700;
  border-color: #ff6700;
}

.submit-btn:hover {
  background-color: #ff8533;
  border-color: #ff8533;
}

/* 响应式调整 */
@media (max-width: 992px) {
  .order-content-wrapper {
    flex-direction: column;
  }
  
  .order-summary {
    width: 100%;
    position: static;
    margin-top: 20px;
  }
  
  .address-item,
  .add-address {
    width: 100%;
  }
}
</style>
